package cn.yiya.shiji.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import cn.yiya.shiji.R;
import cn.yiya.shiji.activity.OrderListActivity;
import cn.yiya.shiji.activity.ShoppingCartActivity;
import cn.yiya.shiji.business.ApiRequest;
import cn.yiya.shiji.business.HttpMessage;
import cn.yiya.shiji.business.MsgCallBack;
import cn.yiya.shiji.business.RetrofitRequest;
import cn.yiya.shiji.entity.OrderListInfo;
import cn.yiya.shiji.views.InterceptLinearLayout;
import cn.yiya.shiji.views.ProgressDialog;

/**
 * Created by jerry on 2016/2/23.
 */
public class OrderListAdapter extends RecyclerView.Adapter<OrderListAdapter.OrderListViewHolder> {
    public ArrayList<OrderListInfo> arrayList;
    private Context context;
    private CountDownTimer timer;
    private Handler handler;
    private SimpleDateFormat mTimeFormat;
    private DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private long diff;
    private final int WAITTINGPAY = 1;
    public final int OTHER = 2;
    public final int SHAREORDER = 3;
    private int source = 0;                                      // 未付款
    private Hint hint;


    private static final int TRANSITTING = 3;                   // 运输中
    private static final int DONE = 4;                          // 已完成
    private static final int DISABLE = 5;                      // 失效
    private static final String REFUNDTAG = "14";               // 退款后失效标签
    private static final int INTERVAL = 1000;                   // 倒计时间隔(1000毫秒)

    public OrderListAdapter(Context context, Handler handler) {
        this.context = context;
        this.handler = handler;
        mTimeFormat = new SimpleDateFormat("mm:ss");
    }

    public OrderListAdapter(Context context, Handler handler, int source) {
        this.context = context;
        this.handler = handler;
        this.source = source;
        mTimeFormat = new SimpleDateFormat("mm:ss");

    }

    @Override
    public OrderListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == WAITTINGPAY) {
            return new OrderListViewHolder(LayoutInflater.from(context).inflate(R.layout.order_item_wait_pay_layout, parent, false));
        } else {
            return new OrderListViewHolder(LayoutInflater.from(context).inflate(R.layout.order_item_layout, parent, false));
        }
    }

    @Override
    public void onBindViewHolder(final OrderListViewHolder holder, final int position) {
        holder.setIsRecyclable(false);
        switch (holder.getItemViewType()) {
            case WAITTINGPAY:
                waitToPay(holder, position);                                                        // 等待付款
                break;
            case OTHER:
                otherStatus(holder, position);                                                       // 其他的状态
                break;
        }
        int count = 0;
        for (int i = 0; i < arrayList.get(position).getGoods().size(); i++) {
            count += arrayList.get(position).getGoods().get(i).getNum();
        }
        SpannableString spannableString = new SpannableString("共 " + count + " 件");
        spannableString.setSpan(new ForegroundColorSpan(0xFF3c3c3c), 2, spannableString.length() - 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new AbsoluteSizeSpan(14, true), 2, spannableString.length() - 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new StyleSpan(Typeface.BOLD), 2, spannableString.length() - 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        holder.tvTotal.setText(spannableString);
        String str = "订单金额:  ¥";
        if (holder.getItemViewType() == WAITTINGPAY) {
            str = "应付金额:  ¥";
        }
        SpannableString spannable = new SpannableString(str + arrayList.get(position).getAmount());
        spannable.setSpan(new ForegroundColorSpan(0xFFed5137), 7, spannable.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannable.setSpan(new AbsoluteSizeSpan(14, true), 5, spannable.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannable.setSpan(new StyleSpan(Typeface.BOLD), 5, spannable.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        holder.tvAmount.setText(spannable);
        holder.tvDate.setText(arrayList.get(position).getCreate_time().substring(0, 10));
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        holder.recyclerView.setLayoutManager(linearLayoutManager);
        HorOrderListAdapter horOrderListAdapter = new HorOrderListAdapter(context, arrayList.get(position).getGoods());
        holder.recyclerView.setAdapter(horOrderListAdapter);
        holder.llGoods.setOnClickingListener(new InterceptLinearLayout.OnClickingListener() {
            @Override
            public void OnClickingListener() {
                if (onItemClickListener != null) {
                    onItemClickListener.onItemClick(arrayList.get(position).getOrder_number(),
                            arrayList.get(position).getSub_order_number(), OTHER);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        if (arrayList == null) {
            return 0;
        }
        return arrayList.size();
    }

    class OrderListViewHolder extends RecyclerView.ViewHolder {
        TextView tvOrderNum, tvAmount, tvTotal, tvPay, tvDate;
        RelativeLayout relativeLayout;
        RecyclerView recyclerView;
        TextView tvDes;
        LinearLayout llTv;
        InterceptLinearLayout llGoods;

        public OrderListViewHolder(View itemView) {
            super(itemView);
            tvOrderNum = (TextView) itemView.findViewById(R.id.tvorder);
            tvAmount = (TextView) itemView.findViewById(R.id.tv_amount);
            tvTotal = (TextView) itemView.findViewById(R.id.tv_total);
            tvPay = (TextView) itemView.findViewById(R.id.tv_pay);
            relativeLayout = (RelativeLayout) itemView.findViewById(R.id.rl_order);
            recyclerView = (RecyclerView) itemView.findViewById(R.id.recyler_view);
            tvDate = (TextView) itemView.findViewById(R.id.tv_date);
            tvDes = (TextView) itemView.findViewById(R.id.tv_des);
            llTv = (LinearLayout) itemView.findViewById(R.id.ll_tv);
            llGoods = (InterceptLinearLayout) itemView.findViewById(R.id.linearlayout);
        }
    }

    private OnItemClickListener onItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener {
        void onItemClick(String orderno, String suborderno, int type);
    }

    public ArrayList<OrderListInfo> getArrayList() {
        return arrayList;
    }

    public void setArrayList(ArrayList<OrderListInfo> arrayList) {
        this.arrayList = arrayList;
    }

    private void gobackShoppingCar(String orderNum) {
        new RetrofitRequest<>(ApiRequest.getApiShiji().gobackShoppingCar(orderNum)).handRequest(new MsgCallBack() {
            @Override
            public void onResult(HttpMessage msg) {
                if (msg.isSuccess()) {
                    ProgressDialog.showCommonScrollDialogCancel(context, "提示", "您已成功将订单内的商品加回购物车", "返回", "查看购物车",
                            new ProgressDialog.DialogClick() {
                                @Override
                                public void OkClick() {
                                    Intent intent = new Intent();
                                    intent.setClass(context, ShoppingCartActivity.class);
                                    ((OrderListActivity)context).startActivityForResult(intent, OrderListActivity.REQUEST_CAR);
                                }

                                @Override
                                public void CancelClick() {

                                }
                            });
                }
            }
        });
    }

    @Override
    public int getItemViewType(int position) {
        if (arrayList.get(position).getGroup_info().getGroup() == 1) {
            return WAITTINGPAY;
        } else {
            return OTHER;
        }
    }

    public interface Hint {
        void hint();
    }

    public void setHint(Hint hint) {
        this.hint = hint;
    }

    /**
     * 等待付款的item逻辑
     *
     * @param holder
     * @param position
     */
    private void waitToPay(final OrderListViewHolder holder, final int position) {                   // 等待付款item
        if (source == 1) {
            holder.tvOrderNum.setText("订单号 :" + arrayList.get(position).getOrder_number());
            holder.tvDes.setText(R.string.go_to_pay);
            try {
                Date d1 = df.parse(arrayList.get(position).getCurrent_time());
                Date d2 = df.parse(arrayList.get(position).getClose_time());
                if (arrayList.get(position).getDiff() == 0) {
                    diff = d2.getTime() - d1.getTime();
                } else {
                    diff = arrayList.get(position).getDiff();
                }

            } catch (Exception e) {

            }

            holder.tvPay.setVisibility(View.VISIBLE);
            timer = new CountDownTimer(diff, INTERVAL) {
                @Override
                public void onTick(long millisUntilFinished) {
                    holder.tvPay.setText(mTimeFormat.format(new Date(millisUntilFinished)));
                    if (millisUntilFinished != 0) {
                        arrayList.get(position).setDiff(millisUntilFinished);
                    }
                }

                @Override
                public void onFinish() {                                   // 倒计时结束的操作
                    holder.llTv.setBackgroundColor(0xFFd8d8d8);
                }
            };
            timer.start();

        } else {
            holder.tvOrderNum.setText("等待付款");
            holder.tvOrderNum.setTextColor(0xFFed5137);
            holder.tvDes.setText(R.string.go_to_pay);
            try {
                Date d1 = df.parse(arrayList.get(position).getCurrent_time());
                Date d2 = df.parse(arrayList.get(position).getClose_time());
                if (arrayList.get(position).getDiff() == 0) {
                    diff = d2.getTime() - d1.getTime();
                } else {
                    diff = arrayList.get(position).getDiff();
                }
            } catch (Exception e) {

            }
            holder.tvPay.setVisibility(View.VISIBLE);
            timer = new CountDownTimer(diff, INTERVAL) {
                @Override
                public void onTick(long millisUntilFinished) {
                    holder.tvPay.setText(mTimeFormat.format(new Date(millisUntilFinished)));
                    arrayList.get(position).setDiff(millisUntilFinished);
                }

                @Override
                public void onFinish() {
                    holder.tvOrderNum.setText("等待付款");
                    holder.tvOrderNum.setTextColor(0xFF9e9e9e);
                    holder.tvPay.setText("");
                    holder.tvDes.setText(R.string.go_back_shopping_cart);
                }
            };
            timer.start();
        }
        initEvent(holder.llTv, arrayList.get(position).getOrder_number(),
                arrayList.get(position).getSub_order_number(), OTHER);
    }

    /**
     * 其他状态下的item逻辑
     *
     * @param holder
     * @param position
     */
    private void otherStatus(final OrderListViewHolder holder, final int position) {                 // 未付款，运输中，已完成， 失效 item
        switch (arrayList.get(position).getGroup_info().getGroup()) {
            case TRANSITTING:                // 运输中
                if (source == 2) {
                    holder.tvOrderNum.setText("运输中");
                    holder.tvOrderNum.setTextColor(Color.parseColor("#0c0c0c"));
                    holder.tvPay.setText("");
                } else {
                    holder.tvOrderNum.setText("订单号 :" + arrayList.get(position).getOrder_number());
                    holder.tvPay.setText("");
                }
                holder.tvDes.setText(R.string.goto_Share);
                initEvent(holder.llTv, arrayList.get(position).getOrder_number(),
                        arrayList.get(position).getSub_order_number(), SHAREORDER);
                break;
            case DONE:                    // 已完成
                if (source == 2) {
                    holder.tvOrderNum.setText("已完成");
                    holder.tvPay.setText("");
                    holder.tvOrderNum.setTextColor(Color.parseColor("#0c0c0c"));
                    holder.tvDes.setText(R.string.goto_Share);
                } else {
                    holder.tvOrderNum.setText("订单号:" + arrayList.get(position).getOrder_number());
                    holder.tvPay.setText("");
                    holder.tvDes.setText(R.string.goto_Share);
                }
                initEvent(holder.llTv, arrayList.get(position).getOrder_number(),                   // 去晒单
                        arrayList.get(position).getSub_order_number(), SHAREORDER);
                break;
            case DISABLE:            // 失效
                if (source == 2) {
                    holder.tvOrderNum.setText("已失效");
                    holder.tvOrderNum.setTextColor(Color.parseColor("#9b9b9b"));
                    holder.tvPay.setText("");
                    holder.tvDes.setText(R.string.go_back_shopping_cart);
                } else {
                    holder.tvOrderNum.setText("订单号 :" + arrayList.get(position).getOrder_number());
                    holder.tvPay.setText("");
                    holder.tvDes.setText(R.string.go_back_shopping_cart);
                }
                if (arrayList.get(position).getStatus().equals(REFUNDTAG)) {
                    holder.llTv.setVisibility(View.GONE);
                }
                holder.llTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        gobackShoppingCar(arrayList.get(position).getOrder_number());
                    }
                });
                break;
        }
    }

    private void initEvent(View view, final String orderNum, final String SubOrderNum, final int status) {
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onItemClickListener != null) {
                    onItemClickListener.onItemClick(orderNum,
                            SubOrderNum, status);
                }
            }
        });
    }
}
